<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="decrement">-</button>
  <span id="count">0</span>
  <button id="increment">+</button>
</body>
</html>
 <script src="https://cdn.bootcdn.net/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script>
// 1.定义reducer函数
// reducer函数接收两个参数，第一个参数是上一次的状态即初始状态，第二个参数是action对象
function reducer(state = {count: 0}, action) {
  if (action.type === 'INCREMENT') {
    return {count: state.count + 1}
  }
  if (action.type === 'DECREMENT') {
    return {count: state.count - 1}
  }
  return state
}
// 2.使用reducer函数生成store实例
const store = Redux.createStore(reducer)

// 3.通过store实例的subscribe订阅数据变化
store.subscribe(() => {
  console.log("state变化了");
  const state = store.getState()
  // 5.通过store实例的getState方法获取最新状态更新到视图中
  document.getElementById('count').innerText = state.count
})

// 4.通过实例的dispatch函数提交action更改状态
const inBtn = document.getElementById('increment')
inBtn.addEventListener('click', () => store.dispatch({type: 'INCREMENT'}))

const deBtn = document.getElementById('decrement')
deBtn.addEventListener('click', () => store.dispatch({type: 'DECREMENT'}))

</script>